package com.jeeplus.modules.sys.web.WXWork;

import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.CacheUtils;
import com.jeeplus.common.utils.HttpUtils;
import com.jeeplus.core.mapper.JsonMapper;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sys.utils.SHA1;
import com.jeeplus.modules.sys.utils.SignUtil;
import com.jeeplus.modules.sys.utils.WxException;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.aspectj.weaver.SignatureUtils;
import org.quartz.SimpleTrigger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.weixin4j.Weixin;
import org.weixin4j.http.HttpClient;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
/**
 * @author Administrator
 * @title: 企业微信
 * @projectName JeePlus
 * @description: TODO
 * @date 2019/9/2412:38
 */
@Controller
@RequestMapping(value = "${apiPath}/WXWork/")
@CrossOrigin
public class WxApiController extends BaseController {
    @Autowired
    WxException wxException;
    @RequestMapping(value = "test")
    @ResponseBody
    public AjaxJson getTest(HttpServletRequest request, HttpServletResponse response) throws IOException {
        AjaxJson ajaxJson = new AjaxJson();
        return ajaxJson;
    }
    @RequestMapping(value = "index")
    public String index(HttpServletRequest request,HttpServletResponse response) {
//        model.addAttribute("value", request.getParameter("value"));
        return "modules/WXWork/index";
    }
    //region 视图

    //endregion
    //region 数据

    //endregion
    //region 系统功能
    /***
     * 获取认证信息
     * @Author LH
     * @Description //TODO
     * @Date 15:12 2019/9/24
     * @param request
     * @param response
     * @param code
     * @param state
     * @return com.jeeplus.common.json.AjaxJson
     **/
    @RequestMapping(value = "Authorize")
//    @ResponseBody
    public String Authorize(HttpServletRequest request, HttpServletResponse response, String code, String state, Model model) {
        String token = CacheUtils.get("WXWork.access_token").toString();
        String pageUrl="modules/WXWork/Authorize";
        String errorUrl="error/wxError";
        try {
            if(token.isEmpty()){
                GetToken(request,response);
                token = CacheUtils.get("WXWork.access_token").toString();
            }
            String url =
                    MessageFormat.format("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={1}&code={0}", code, token);

            System.out.println(url);
            String str = HttpUtils.sendGet(url, "");
            System.out.println(str);
            JSONObject jsonObject = JSONObject.fromObject(str);
            if(jsonObject.getInt("errcode")!=0){
                model.addAttribute("error", wxException.errorMsg(jsonObject.getInt("errcode")));
                return errorUrl;
            }

            String userId = jsonObject.getString("UserId");
            String str1 = MessageFormat.format(
                    "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={1}&userid={0}", userId, token);
            String userInfo = HttpUtils.sendGet(str1, "");
            logger.error(userInfo);
            JSONObject obj=jsonObject.fromObject(userInfo);
            if(obj.getInt("errcode")==0)
            {
                logger.error(obj.getString("name"));
                model.addAttribute("UserId", obj.getString("name"));
            }
            else {
                //model.addAttribute("error", obj.getString("errmsg"));
                return errorUrl;
            }

        }catch (Exception e)
        {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return pageUrl;
    }

    /**
     * 获取应用Token信息
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "GetToken")
    @ResponseBody
    public AjaxJson GetToken(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        String url =
                MessageFormat.format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}", Global.getConfig("WXKork.CorpId"), Global.getConfig("WXKork.CorpSecret"));
        String str = HttpUtils.sendGet(url, "");
        JSONObject jsonObject = JSONObject.fromObject(str);
        logger.error(str);
        if (jsonObject.getString("errcode").equals("0")) {
            ajaxJson.setSuccess(true);
            ajaxJson.setMsg(jsonObject.getString("access_token"));
            CacheUtils.put("WXWork.access_token",jsonObject.getString("access_token"));
            Global.modifyConfig("WXWork.access_token",jsonObject.getString("access_token"));
        } else {
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg(jsonObject.getString("errcode"));
        }
        return ajaxJson;
    }
    /***
     * 给客户发送消息
     *
     * @Author LH
     * @Description //TODO
     * @Date 15:12 2019/9/24
     * @param request
     * @param response
     * @return com.jeeplus.common.json.AjaxJson
     **/
    @RequestMapping(value = "UserMessageSnd")
    @ResponseBody
    public AjaxJson UserMessageSnd(HttpServletRequest request,HttpServletResponse response,String UserId,String content){
        AjaxJson ajaxJson=new AjaxJson();
        ajaxJson.setSuccess(false);
        ajaxJson.setMsg("消息发送失败");
        try {
            String token = CacheUtils.get("WXWork.access_token").toString();
            if(token.isEmpty()){
                GetToken(request,response);
                token = CacheUtils.get("WXWork.access_token").toString();
            }
            String url = MessageFormat.format("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={0}",token);
            Map<String,Object> jsonData=new HashMap<>();
            jsonData.put("touser",UserId);
            jsonData.put("toparty","");
            jsonData.put("totag","");
            jsonData.put("msgtype","text");
            jsonData.put("agentid",1000015);
            Map<String,Object> mapText=new HashMap<>();
            mapText.put("content",content);
            jsonData.put("text",mapText);
            jsonData.put("safe",0);
            String str = HttpUtils.sendPost(url, JsonMapper.toJsonString(jsonData));
            System.out.println(str);
            ajaxJson.setSuccess(true);
            ajaxJson.setMsg("消息发送成功");
        }
        catch (Exception e){
            logger.error(e.getMessage());
        }
        return ajaxJson;
    }
    /***
     * 获取应用的jsapi_ticket
     *
     * @Author LH
     * @Description //TODO
     * @Date 9:36 2019/9/26
     * @param request
     * @param response
     * @return com.jeeplus.common.json.AjaxJson
     **/
    @RequestMapping(value = "getAgentJsapiTicket")
    @ResponseBody
    public AjaxJson GetAgentJsapiTicket(HttpServletRequest request,HttpServletResponse response){
        AjaxJson ajaxJson=new AjaxJson();
        try {
            String token = CacheUtils.get("WXWork.access_token").toString();
            if(token.isEmpty()){
                GetToken(request,response);
                token = CacheUtils.get("WXWork.access_token").toString();
            }
            logger.error(token);
            String url=MessageFormat.format("https://qyapi.weixin.qq.com/cgi-bin/ticket/get?access_token={0}&type=agent_config",token);
            String str=HttpUtils.sendGet(url,"");
            JSONObject jsonObject=JSONObject.fromObject(str);
            if(jsonObject.getString("errcode").equals("0")){
                CacheUtils.put("AgentTicket",jsonObject.getString("ticket"));
                ajaxJson.setMsg(jsonObject.getString("ticket"));
                ajaxJson.setSuccess(true);
                return ajaxJson;
            }
            else {
                ajaxJson.setSuccess(false);
                ajaxJson.setMsg(jsonObject.getString("errmsg"));
            }
        }
        catch (Exception e){
            ajaxJson.setMsg("操作异常");
            ajaxJson.setSuccess(false);
            logger.error(e.getMessage());
        }
        return ajaxJson;
    }
    /***
     * 获取企业的jsapi_ticket
     *
     * @Author LH
     * @Description //TODO
     * @Date 9:36 2019/9/26
     * @param request
     * @param response
     * @return com.jeeplus.common.json.AjaxJson
     **/
    @RequestMapping(value = "getCorpJsapiTicket")
    @ResponseBody
    public AjaxJson GetCorpJsapiTicket(HttpServletRequest request,HttpServletResponse response){
        AjaxJson ajaxJson=new AjaxJson();
        try {
            Object token = CacheUtils.get("WXWork.access_token");
            if(token==null ||token.toString().isEmpty()){
                GetToken(request,response);
                token = CacheUtils.get("WXWork.access_token").toString();
            }
            logger.error(token.toString());
            String url=MessageFormat.format("https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token={0}&type=agent_config",token);
            String str=HttpUtils.sendGet(url,"");
            logger.info(str);
            JSONObject jsonObject=JSONObject.fromObject(str);
            if(jsonObject.getString("errcode").equals("0")){
                CacheUtils.put("CorpTicket",jsonObject.getString("ticket"));
                ajaxJson.setMsg(jsonObject.getString("ticket"));
                ajaxJson.setSuccess(false);
                return ajaxJson;
            }
            else {
                ajaxJson.setSuccess(false);
                ajaxJson.setMsg(jsonObject.getString("errmsg"));
            }
        }
        catch (Exception e){
            ajaxJson.setMsg("操作异常");
            ajaxJson.setSuccess(false);
            logger.error(e.getMessage());
        }
        return ajaxJson;
    }
    /***
     * 服务签名生成
     *
     * @Author LH
     * @Description //TODO
     * @Date 15:44 2019/9/26
     * @param response
     * @param request
     * @return com.jeeplus.common.json.AjaxJson
     **/
    @RequestMapping(value = "getGenerateSignature")
    @ResponseBody
    public AjaxJson GetGenerateSignature(HttpServletResponse response,HttpServletRequest request){
        AjaxJson ajaxJson=new AjaxJson();
        ajaxJson.setMsg("操作错误");
        ajaxJson.setSuccess(false);
        try {
            String url=request.getParameter("url");
            String nonce = SignUtil.getNonceStr(16);
            String time =  SignUtil.getTimestamp();
            String tick="";
            if(CacheUtils.get("CorpTicket")==null){
                GetCorpJsapiTicket(request,response);
            }
            tick=CacheUtils.get("CorpTicket").toString();
            if(tick.isEmpty())
            {
                GetCorpJsapiTicket(request,response);
            }
            tick=CacheUtils.get("CorpTicket").toString();
            //url="http://k26894v027.wicp.vip/index";
            Map<String,Object> map=SignUtil.GenerateSignature(url,tick);
            System.out.println(map);
            CacheUtils.put("Signature",map.get("signature"));
            ajaxJson.setMsg(JsonMapper.toJsonString(map));
            ajaxJson.setSuccess(true);
            return ajaxJson;
        }
        catch (Exception e){
            logger.error(e.getMessage());
            ajaxJson.setMsg("操作异常");
            ajaxJson.setSuccess(false);
        }
        return ajaxJson;
    }
    /***
     * 应用签名生成
     *
     * @Author LH
     * @Description //TODO
     * @Date 15:44 2019/9/26
     * @param response
     * @param request
     * @return com.jeeplus.common.json.AjaxJson
     **/
    @RequestMapping(value = "getGenerateAgeentSignature")
    @ResponseBody
    public AjaxJson GetGenerateAgeentSignature(HttpServletResponse response,HttpServletRequest request){
        AjaxJson ajaxJson=new AjaxJson();
        ajaxJson.setMsg("操作错误");
        ajaxJson.setSuccess(false);
        try {
            String url=request.getParameter("url");
            String nonce = SignUtil.getNonceStr(16);
            String time =  SignUtil.getTimestamp();
            String tick="";
            if(CacheUtils.get("AgentTicket")==null){
                GetCorpJsapiTicket(request,response);
            }
            tick=CacheUtils.get("AgentTicket").toString();
            if(tick.isEmpty())
            {
                GetCorpJsapiTicket(request,response);
            }
            tick=CacheUtils.get("AgentTicket").toString();
            Map<String,Object> map=SignUtil.GenerateSignature(url,tick);
            System.out.println(map);
            CacheUtils.put("AgeentSignature",map.get("signature"));
            ajaxJson.setMsg(JsonMapper.toJsonString(map));
            ajaxJson.setSuccess(true);
            return ajaxJson;
        }
        catch (Exception e){
            logger.error(e.getMessage());
            ajaxJson.setMsg("操作异常");
            ajaxJson.setSuccess(false);
        }
        return ajaxJson;
    }
    @RequestMapping(value = "getConfig")
    @ResponseBody
    public AjaxJson GetConfig(HttpServletRequest request,HttpServletResponse response){
        AjaxJson ajaxJson=new AjaxJson();
        ajaxJson.setSuccess(false);
        ajaxJson.setMsg("操作错误");
        Map<String,Object> map=new HashMap<>();
        try {
            String url=request.getParameter("url");
            String CorpTicket=CacheUtils.get("CorpTicket").toString();
            if(CorpTicket.isEmpty()){
                GetCorpJsapiTicket(request,response);
                CorpTicket=CacheUtils.get("CorpTicket").toString();
            }
            String AgeentTicket=CacheUtils.get("AgentTicket").toString();
            if(AgeentTicket.isEmpty()){
                GetAgentJsapiTicket(request,response);
                AgeentTicket=CacheUtils.get("AgentTicket").toString();
            }
            Map<String,Object> SignatureMap=SignUtil.GenerateSignature(url,CorpTicket);
            Map<String,Object> AgeentSignatureMap=SignUtil.GenerateSignature(url,AgeentTicket);
            map.put("core",SignatureMap);
            map.put("agent",AgeentSignatureMap);
            ajaxJson.setMsg(JsonMapper.toJsonString(map));
            ajaxJson.setSuccess(true);
            logger.error(JsonMapper.toJsonString(map));
        }
        catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            ajaxJson.setMsg("操作异常");
            ajaxJson.setSuccess(false);

        }
        return ajaxJson;
    }
    //endregion
}
